﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace PIM_ATE.Mods
{
    class PIMProcessForModule : PIMProcess
    {
        object m_handle;
        InstrumentGroup m_instr;
        JcPIMRunner m_pimObj;

        ClsDataProduct m_productObj;
        ClsDataUser m_userObj;
        ClsWebRecord m_resultObj;
        ClsDataCalibrationBuilder m_cal_builder;
        ClsDataCalibration m_calObj;
        ClsDataSetupBuilder m_setup_builder;
        ClsDataSetup m_setupObj;
        JcPIMInstrumentInfo[] m_devices;

        #region PIMProcess Param
        bool m_isKnockState;
        int m_process_index = 0;
        bool m_isAllFail = false;
        bool m_isNeedQuit = false;

        bool m_ThirdFail_Flag;
        List<double> m_ThirdFail_lstValue;
        DateTime m_timeStart;
        DateTime m_timeStop;

        ClsDataConfig m_config;
        List<ClsDataConfig> m_lstConifg;

        Dictionary<int, JcPIMRecordResult> m_dicResults;
        ModTestMode m_ModTestMode;
        #endregion

        public PIMProcessForModule(object handle, JcPIMInstrumentInfo[] infos, InstrumentGroup pimType)
        {
            m_handle = handle;
            m_instr = pimType;
            m_isKnockState = false;
            m_ThirdFail_Flag = false;
            m_ThirdFail_lstValue = new List<double>();
            m_dicResults = new Dictionary<int, JcPIMRecordResult>();
            m_resultObj = new ClsWebRecord(pimType);
            m_cal_builder = new ClsDataCalibrationBuilder(GDefine.DBNameMOD);
            m_setup_builder = new ClsDataSetupBuilder(GDefine.DBNameMOD);
            m_devices = infos;

            if (m_instr == InstrumentGroup.MULTI_BAND)
            {
                m_pimObj = new JcPIMForMultiBand(infos[0].instrAddress);
            }
            else if (m_instr == InstrumentGroup.RFDESKTOP)
            {
                var dicDevices = JcPIMDevicesBuilder.dicDevices;
                m_pimObj = new rflight.ClsRfPIMforDesktop(dicDevices);
            }
            else
            {
                var dicDevices = JcPIMDevicesBuilder.dicDevices;
                m_pimObj = new JcPIMForCompat(dicDevices);
            }
            m_pimObj.evt_show_error_handle += m_pimObj_evt_show_error_handle;
            m_pimObj.evt_show_log_handle += m_pim_evt_show_log_handle;
            m_pimObj.evt_complete_test_handle += m_pim_evt_complete_test_handle;
            m_pimObj.evt_get_point_handle += m_pim_evt_getPoint_test_handle;

        }

        #region event

        void evt_PIMProcess_Close(object sender, EventArgs e)
        {
            On_evt_log_handle("", new EventLoggingArgs(true, null, true));
            On_evt_log_handle("PIMPorcess: 测试结束", null);
            On_evt_complete_all_process_handle(sender, e);
        }

        void m_pim_evt_getPoint_test_handle(object sender, EventArgs e)
        {
            if (sender == null) return;
            JcPIMDataResults result = sender as JcPIMDataResults;
            result.Im_V = (float)Math.Round(result.Im_V, 1);
            result.Im_V_NotFix = result.Im_V;
            double dNeedPower1 = m_config.F1Power + m_config.TXOffset;
            double dNeedPower2 = m_config.F2Power + m_config.TXOffset;

            //42.65   43.35    紫光0.35  纳特设备放宽0.6  
            if (result.P1 < dNeedPower1 - 0.35 || result.P1 > dNeedPower1 + 0.35)
            {
                m_isNeedQuit = true;
                (m_handle as FrmMods).Tips(string.Format("P1功率超出范围 P1={0},F1={1}请重试", result.P1, result.F1), 0);
                On_evt_log_handle("PIMProcess: P1功率超出范围,请重试", null);
                m_pimObj.stop_test();
                return;
            }
            //0.35
            if (result.P2 < dNeedPower2 - 0.35 || result.P2 > dNeedPower2 + 0.35)
            {
                m_isNeedQuit = true;
                (m_handle as FrmMods).Tips(string.Format("P2功率超出范围 P2={0},F2={1}请重试", result.P2,result.F2), 0);
                On_evt_log_handle("PIMProcess:  P2功率超出范围,请重试", null);
                m_pimObj.stop_test();
                return;
            }

            if (m_config.SpecUnit.ToLower().Contains("dbc"))
            {
                result.Im_V -= 43;
            }

            if (m_setupObj.IsCheckOn)
            {
                double f1 = 0, f2 = 0;
                PIMFunction.formateSpec(m_config.SpecReg, ref f1, ref f2);
                result.Im_V_NotFix = result.Im_V;
                result.Im_V = (float)PIMFunction.getCheckValue(result.Im_V, f2, m_config.Check);
            }

            if (m_ThirdFail_lstValue.Count < 3)
            {
                m_ThirdFail_lstValue.Add(result.Im_V);
            }
            else
            {
                m_ThirdFail_lstValue.RemoveAt(0);
                m_ThirdFail_lstValue.Add(result.Im_V);
            }
            if (m_ThirdFail_lstValue.Count == 3)
            {
                if (!PIMFunction.compareSpec(m_ThirdFail_lstValue[0], m_config.SpecReg) &&
                    !PIMFunction.compareSpec(m_ThirdFail_lstValue[1], m_config.SpecReg) &&
                    !PIMFunction.compareSpec(m_ThirdFail_lstValue[2], m_config.SpecReg))
                {
                    m_ThirdFail_Flag = true;
                    m_pimObj.stop_test();
                }
            }

            EventProcessArgs ePorcess = new EventProcessArgs();
            ePorcess.processNum = m_lstConifg.IndexOf(m_config);
            ePorcess.processObj = m_config;
            On_evt_get_results_handle(sender, ePorcess);
        }

        void m_pim_evt_complete_test_handle(object sender, EventArgs e)
        {
            if (sender == null || m_isNeedQuit)
            {
                evt_PIMProcess_Close(null, null);
                return;
            }

            List<JcPIMDataResults> results = sender as List<JcPIMDataResults>;

            if (results.Count == 0)
            {
                On_evt_log_handle("PIMPorcess: 配置的TX和RX频段无法产生互调点", null);
                evt_PIMProcess_Close(null, null);
                return;
            }

            int index = -1;
            float max = PIMFunction.getMax(results, out index);
            bool bFailResult = !PIMFunction.compareSpec(max, m_config.SpecReg);

            if (m_dicResults.ContainsKey(m_process_index))
            {
                m_dicResults[m_process_index].fValue = max;
                m_dicResults[m_process_index].index = index;
                m_dicResults[m_process_index].sPass = bFailResult ? GDefine.ContentFail2 : GDefine.ContentPass2;

                if (!m_isKnockState && m_config.IsSweepTest && m_config.IsKnock)
                    m_dicResults[m_process_index].valus_knock = results.ToArray();
                else
                    m_dicResults[m_process_index].valus = results.ToArray();
            }
            else
            {
                var result = new JcPIMRecordResult();
                result.fValue = max;
                result.index = index;
                result.sPass = bFailResult ? GDefine.ContentFail2 : GDefine.ContentPass2;
                result.valus = results.ToArray();
                result.valus_knock = null;
                m_dicResults.Add(m_process_index, result);
            }

            if (/*!m_ThirdFail_Flag &&*/!bFailResult && m_isKnockState && m_config.IsSweepTest)
            {
                KnockProcessRun(results[index]);
                return;
            }

            if (m_config.IsKnock)
            {
                //On_evt_log_handle("", new EventLoggingArgs(true, null));
                On_evt_log_handle("", new EventLoggingArgs(false, null));
            }

            EventProcessArgs eProcess = new EventProcessArgs();
            eProcess.processNum = m_lstConifg.IndexOf(m_config);
            eProcess.processState = bFailResult;
            eProcess.processObj = max;
            On_evt_complete_process_handle(sender, eProcess);

            m_process_index++;

            if (bFailResult)
            {
                if ((m_handle as FrmMods).selectTips("当前测试项 不合格") == 1)
                {
                    m_process_index--;
                }
                else
                {
                    m_isAllFail = bFailResult;
                }
            }

            if (m_process_index < m_lstConifg.Count)
            {
                PIMProcessRun();
            }
            else
            {
                if (m_ModTestMode == ModTestMode.Second)
                {
                    DataProcessUploadSecondTest();
                }
                else
                {
                    if (!GDefine.IS_CONBINED_BAND)
                    {
                        Data();
                    }
                    else
                    {
                        MB_B = true;
                        m_timeStop = DateTime.Parse(PIMFunction.getTime("MOD"));
                        DataProcessUpload();
                    }                  
                }               
                evt_PIMProcess_Close("测试完成", null);
            }
        }
        public override void TestStop()
        {
            //On_evt_log_handle("", new EventLoggingArgs(true, null));
            m_pimObj.stop_test();
        }

        public override void OverTest()
        {

            m_pimObj.stop_test();
            m_process_index = m_lstConifg.Count - 1;
            m_isNeedQuit = true;
        }

        void m_pim_evt_getPoint_cal_handle(object sender, EventArgs e)
        {
            if (sender == null) return;
            JcPIMDataResults result = sender as JcPIMDataResults;
            result.Im_V = (float)Math.Round(result.Im_V, 1);
            //42.65   43.35    紫光0.35  纳特设备放宽0.6  
           
            if (result.P1 < 42.65 + m_calObj.TXOffset || result.P1 > 43.35 + m_calObj.TXOffset)
            {
                m_isNeedQuit = true;
                (m_handle as FrmMods).Tips(string.Format("P1功率超出范围 P1={0},F1={1}请重试", result.P1, result.F1), 0);
                On_evt_log_handle("PIMProcess: P1功率超出范围", null);
                m_pimObj.stop_test();
                return;
            }

            if (result.P2 < 42.65 + m_calObj.TXOffset || result.P2 > 43.35 + m_calObj.TXOffset)
            {
                m_isNeedQuit = true;
                (m_handle as FrmMods).Tips(string.Format("P2功率超出范围 P2={0},F2={1}请重试", result.P2,result.F2), 0);
                On_evt_log_handle("PIMProcess:  P2功率超出范围", null);
                m_pimObj.stop_test();
                return;
            }

            EventProcessArgs ePorcess = new EventProcessArgs();
            ePorcess.processNum = -1;
            ePorcess.processObj = null;
            On_evt_get_results_handle(sender, ePorcess);
        }

        void m_pim_evt_complete_cal_handle(object sender, EventArgs e)
        {
            m_pimObj.evt_complete_test_handle += m_pim_evt_complete_test_handle;
            m_pimObj.evt_complete_test_handle -= m_pim_evt_complete_cal_handle;
            m_pimObj.evt_get_point_handle += m_pim_evt_getPoint_test_handle;
            m_pimObj.evt_get_point_handle -= m_pim_evt_getPoint_cal_handle;

            if (sender == null)
            {
                evt_PIMProcess_Close(null, null);
                return;
            }

            if (m_isNeedQuit)
            {
                evt_PIMProcess_Close(null, null);
                return;
            }

            List<JcPIMDataResults> results = sender as List<JcPIMDataResults>;

            if (results.Count == 0)
            {
                On_evt_log_handle("PIMPorcess: 配置的TX和RX频段无法产生互调点", null);
                evt_PIMProcess_Close(null, null);
                return;
            }

            int index = -1;
            float max = PIMFunction.getMax(results, out index);

            EventProcessArgs eProcess = new EventProcessArgs();
            eProcess.processNum = -1;
            eProcess.processState = false;
            eProcess.processObj = max;
            On_evt_complete_process_handle(sender, eProcess);
            evt_PIMProcess_Close("测试完成", null);
        }

        void m_pim_evt_show_log_handle(object sender, EventArgs e)
        {
            On_evt_log_handle(sender, null);
        }

        void m_pimObj_evt_show_error_handle(object sender, EventArgs e)
        {
            string msg = sender as string;
            (m_handle as FrmMods).Tips(msg, 0);
        }

        #endregion
        public override bool PIMTestModeSet(ModTestMode mode = ModTestMode.First)
        {
            m_ModTestMode = mode;
            return true;
        }
        public override bool PIMProcessMatchProcode(ClsDataProduct product)
        {
            string sProcode = m_resultObj.ProductTypeID_GetbySN_FromDebugTest(product.sProductSN);
            if (sProcode == null || sProcode == "")
            {
                return false;
            }
            product.sProcode = sProcode;

            string sProcodeName = m_resultObj.ProductTypeName_GetbyProductTypeID(sProcode);
            if (sProcodeName == null || sProcodeName == "")
            {
                return false;
            }
            product.sProcodeName = sProcodeName;

            string sTestStep = "";
            bool bret = false;
            if (m_ModTestMode == ModTestMode.Second)
            {
                sTestStep = m_resultObj.GetTestStep_ForPIMSecondTest_bySN(product.sProductSN);
                bret = m_resultObj.ProductType_Flow_HasValidSevenStep_ForPIMSecondTest(product.sProductSN, product.sProcode);
            }
            else
            {
                sTestStep = m_resultObj.GetTestStep_bySN(product.sProductSN);
                bret = m_resultObj.ProductType_Flow_HasValidSevenStep_ForPIMTest(product.sProductSN, product.sProcode);
            }
            if (sTestStep == null || sTestStep == "")
            {
                return false;
            }
            product.sPIMTestStep = sTestStep;
            if (!bret)
            {
                (m_handle as FrmMods).Tips("级联查询不合格,请返回上一道工序!", 0);
                if (GDefine.IS_NOCHECK_CAL_MOD) return true;
                return false;
            }
            return true;
        }

        public override bool PIMStepCheck(ClsDataProduct product)
        {
            string stepmsg = product.sPIMTestStep;
            int num = 0;
            string text = "";
            if (stepmsg.Contains("返修测试"))
            {
                num = Convert.ToInt32(stepmsg.Substring(4));
                if (num >= 4)
                {
                    text = string.Format("该产品返修次数过多,当前返修次数为{0}，是否继续测试？", num);
                    if (MessageBox.Show(text, "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation) == DialogResult.Cancel)
                    {
                        return false;
                    }
                    else
                    {
                        return true;
                    }
                }
                return true;
            }
            return true;
        }

        public override bool PIMProcessConfig(object objConfigList, ClsDataProduct product, ClsDataUser user)
        {
            if (!GDefine.IS_NOCHECK_CAL_MOD)
            {
                string error = "";
                m_calObj = null;
                m_cal_builder.construct(product.sProcode, user.sEquID);
                m_calObj = m_cal_builder.downloadVaule(ref error);
                if (m_calObj == null)
                {
                    if (error == "") error = "未发现有效校准!";
                    On_evt_log_handle("PIMProcessConfig: " + error, null);
                    (m_handle as FrmMods).Tips(error, 0);
                    evt_PIMProcess_Close(null, null);
                    return false;
                }

                m_setup_builder.construct(product.sProcode);
                m_setupObj = m_setup_builder.downloadVaule(ref error);
                if (m_setupObj == null)
                {
                    if (error == "") error = "未发现有效设置!";
                    On_evt_log_handle("PIMProcessConfig: " + error, null);
                    (m_handle as FrmMods).Tips(error, 0);
                    evt_PIMProcess_Close(null, null);
                    return false;
                }

                DateTime calTime = m_calObj.CalTime.AddHours(m_setupObj.CalTimeLimit);
                if (DateTime.Now > calTime)
                {
                    On_evt_log_handle("PIMProcessConfig: 校准已到期", null);
                    (m_handle as FrmMods).Tips("校准已到期", 0);
                    evt_PIMProcess_Close(null, null);
                    return false;
                }
            }
            else
            {
                m_calObj = new ClsDataCalibration();
                m_setupObj = new ClsDataSetup();
            }

            m_lstConifg = objConfigList as List<ClsDataConfig>;
            m_productObj = product;
            m_userObj = user;

            if (!DataProcessCheck(m_productObj.sProductSN))
            {
                evt_PIMProcess_Close(null, null);
                return false;
            }

            m_isNeedQuit = false;
            m_isAllFail = false;
            m_process_index = 0;
            m_dicResults.Clear();
            return true;
        }

        public override void PIMProcessStrart()
        {
            m_timeStart = DateTime.Parse(PIMFunction.getTime("MOD"));
            PIMProcessRun();
        }

        public override void PIMProcessCalibration(double f1, double f2, double rx1, double rx2, double step, double txoff, double rxoff, int mode)
        {
            JcPIMDataSettings settings = new JcPIMDataSettings();
            string alias = m_devices[0].instrBandAlias;
            settings.Band_Name = JcPIMDevicesBuilder.dicBands[alias].range_name;
            settings.InstrumentType = JcPIMDevicesBuilder.dicDevices[settings.Band_Name].instrType;

            settings.F1Set = f1;
            settings.F2Set = f2;
            settings.RXs = rx1;
            settings.RXe = rx2;
            settings.StepRx = step;

            settings.Offset1 = txoff;
            settings.Offset2 = txoff;
            settings.Offset_RX += rxoff;

            m_calObj = new ClsDataCalibration();
            m_calObj.TXOffset = txoff;
            m_calObj.RXOffset = rxoff;

            if (mode == 0)
            {
                settings.Mode = ImMode.Freq;
            }
            else
            {
                settings.Mode = ImMode.Time;
                settings.F1s = f1;
                settings.F2e = f2;
                settings.Time = 10;
            }

            settings.Unit = ImUnit.dBm;
            settings.TX1 = 43;
            settings.TX2 = 43;
            settings.Band_TX1 = (byte)JcPIMDevicesBuilder.dicDevices[settings.Band_Name].instrBandIndex;
            settings.Band_TX2 = (byte)JcPIMDevicesBuilder.dicDevices[settings.Band_Name].instrBandIndex;
            settings.Band_RX = (byte)JcPIMDevicesBuilder.dicDevices[settings.Band_Name].instrBandIndex;
            settings.Port_TX1 = 0;
            settings.Port_TX2 = 0;
            settings.Port_RX = 0;

            if (!(m_handle as FrmMods).Tips("即将开始校准，请连接标准件"))
            {

                evt_PIMProcess_Close(null, null);
                return;
            }

            On_evt_log_handle("PIMProcess: 开始校准,请稍后...", null);
            m_isNeedQuit = false;
            m_pimObj.evt_complete_test_handle -= m_pim_evt_complete_test_handle;
            m_pimObj.evt_complete_test_handle += m_pim_evt_complete_cal_handle;
            m_pimObj.evt_get_point_handle -= m_pim_evt_getPoint_test_handle;
            m_pimObj.evt_get_point_handle += m_pim_evt_getPoint_cal_handle;
            m_pimObj.start_settings(settings);
            m_pimObj.start_test();
        }

        private void PIMProcessRun()
        {
            if (m_lstConifg.Count > 0 && m_process_index < m_lstConifg.Count)
            {
                while (m_process_index < m_lstConifg.Count)
                {
                    m_config = m_lstConifg[m_process_index];
                    if (m_config.Enable)
                    {
                        break;
                    }
                    else
                    {
                        if (m_process_index == m_lstConifg.Count - 1)
                        {
                            if (m_ModTestMode == ModTestMode.Second)
                            {
                                DataProcessUploadSecondTest();
                            }
                            else
                            {
                                if (!GDefine.IS_CONBINED_BAND)
                                {
                                    Data();
                                }
                                else
                                {
                                    MB_B = true;
                                    m_timeStop = DateTime.Parse(PIMFunction.getTime("MOD"));
                                    DataProcessUpload();
                                }
                            }
                            evt_PIMProcess_Close("测试完成", null);
                            return;
                        }

                        m_process_index++;
                        continue;
                    }
                }

                JcPIMDataSettings settings = toPIMDataSettings(m_config);
                if (settings == null)
                {
                    On_evt_log_handle("PIMPorcess: 配置错误", null);
                    (m_handle as FrmMods).Tips("配置频段和仪表频段不符合", 0);
                    evt_PIMProcess_Close(null, null);
                    return;
                }

                {
                    if (!(m_handle as FrmMods).Tips(string.Format("即将开始测试\r\n通道： {0}\r\n提示： {1}",
                        m_config.ProCH, m_config.Message)))
                    {
                        evt_PIMProcess_Close(null, null);
                        return;
                    }
                }

                if (m_config.IsKnock && !m_config.IsSweepTest)
                {
                    On_evt_log_handle("正在敲击测试，请敲击！", new EventLoggingArgs(true, null));
                }

                On_evt_log_handle(string.Format("PIMPorcess: {0} - {1}", m_config.ProCH, m_config.PIMItemName), null);
                m_isKnockState = m_config.IsKnock;
                m_ThirdFail_lstValue.Clear();
                m_ThirdFail_Flag = false;

                EventProcessArgs eProcess = new EventProcessArgs();
                eProcess.processNum = m_lstConifg.IndexOf(m_config);
                eProcess.processObj = m_config;
                On_evt_set_settings_handle(settings, eProcess);
                m_pimObj.start_settings(settings);
                m_pimObj.start_test();
            }
        }

        private void KnockProcessRun(JcPIMDataResults result)
        {
            On_evt_log_handle("正在敲击测试，请敲击！", new EventLoggingArgs(true, null));

            On_evt_log_handle("KnockPorcess: " + m_config.PIMItemName, null);
            JcPIMDataSettings settings = getResultMaxForKnock(result);
            m_isKnockState = false;
            m_ThirdFail_lstValue.Clear();
            m_ThirdFail_Flag = false;

            EventProcessArgs eProcess = new EventProcessArgs();
            eProcess.processNum = m_lstConifg.IndexOf(m_config);
            eProcess.processObj = m_config;

            On_evt_set_settings_handle(settings, eProcess);
            m_pimObj.start_settings(settings);
            m_pimObj.start_test();
        }

        private bool DataProcessCheck(string sn)
        {
            return true;
        }

        bool MB_B = false;
        private bool DataProcessUpload()
        {
            // m_timeStop = DateTime.Parse(PIMFunction.getTime("MOD"));
            ClsLocalRecord local_record = new ClsLocalRecord(m_productObj, m_timeStop, m_dicResults, m_userObj, m_lstConifg);
            if (!local_record.SaveLocalFile(m_productObj.iMode))
            {
                On_evt_log_handle("DataProcessUpload: SaveLocalFile失败", null);
                return false;
            }
            On_evt_log_handle("DataProcessUpload: 保存本地数据", null);

            if (!m_resultObj.construct(m_isAllFail, m_timeStart, m_timeStop, m_dicResults, m_lstConifg, m_productObj, m_userObj, m_setupObj))
            {
                On_evt_log_handle("DataProcessUpload: construct失败", null);
                return false;
            }

            if (m_productObj.iMode == (int)Running_Mode.ENG || GDefine.IS_LOCAL_RESULT_MOD) return true;
            bool ret;
            if (MB_B)
            {
                ret = m_resultObj.upload_MOBI();
                On_evt_log_handle(string.Format("DataProcessUpload: 保存MOBI数据({0})", ret), null);
                if (!ret)
                    (m_handle as FrmMods).Tips("保存MOBI数据失败！", 0);                   
                if (!GDefine.IS_Repair_AutoBuild)
                {
                    if (m_isAllFail)
                    {
                        ret = m_resultObj.Repair_AutoBuild(m_productObj.sProductSN, m_userObj.sUserID);
                        On_evt_log_handle(string.Format("DataProcessUpload: 进入返修状态({0})", ret), null);
                    }
                }
            }
            if (!GDefine.IS_LOCAL_RESULT_ZTE)
            {
                if (m_resultObj.Isvalid_ProductType_ZTE(m_productObj.sProcode))
                {
                    ret = m_resultObj.upload_ZTE();
                    On_evt_log_handle(string.Format("DataProcessUpload: 保存ZTE数据({0})", ret), null);
                }
            }
            return true;
        }

        private bool DataProcessUpload(List<PIMTestItemInfo> iteminfo)
        {
            m_timeStop = DateTime.Parse(PIMFunction.getTime("MOD"));
            ClsLocalRecord local_record = new ClsLocalRecord(m_productObj, m_timeStop, m_dicResults, m_userObj, m_lstConifg);
            if (!local_record.SaveLocalFile(m_productObj.iMode))
            {
                On_evt_log_handle("DataProcessUpload-new: SaveLocalFile失败", null);
                return false;
            }
            On_evt_log_handle("DataProcessUpload-new: 保存本地数据", null);

            if (!m_resultObj.construct(m_isAllFail, m_timeStart, m_timeStop, m_dicResults, m_lstConifg, m_productObj, m_userObj, m_setupObj))
            {
                On_evt_log_handle("DataProcessUpload-new: construct失败", null);
                return false;
            }

            m_resultObj.AddData(iteminfo);

            if (m_productObj.iMode == (int)Running_Mode.ENG || GDefine.IS_LOCAL_RESULT_MOD) return true;

            bool ret = m_resultObj.upload_MOBI();
            On_evt_log_handle(string.Format("DataProcessUpload-new: 保存MOBI数据({0})", ret), null);
            if (!ret)
                (m_handle as FrmMods).Tips("保存MOBI数据失败！", 0);  
            if (!GDefine.IS_Repair_AutoBuild)
            {
                if (m_isAllFail)
                {
                    ret = m_resultObj.Repair_AutoBuild(m_productObj.sProductSN, m_userObj.sUserID);
                    On_evt_log_handle(string.Format("DataProcessUpload-new: 进入返修状态({0})", ret), null);
                }
            }

            if (!GDefine.IS_LOCAL_RESULT_ZTE)
            {
                if (m_resultObj.Isvalid_ProductType_ZTE(m_productObj.sProcode))
                {
                    ret = m_resultObj.upload_ZTE();
                    On_evt_log_handle(string.Format("DataProcessUpload-new: 保存ZTE数据({0})", ret), null);
                }
            }
            return true;
        }

        private bool DataProcessUploadSecondTest()
        {
            m_timeStop = DateTime.Parse(PIMFunction.getTime("MOD"));
            ClsLocalRecord local_record = new ClsLocalRecord(m_productObj, m_timeStop, m_dicResults, m_userObj, m_lstConifg);
            if (!local_record.SaveLocalFile(m_productObj.iMode, m_ModTestMode))
            {
                On_evt_log_handle("DataProcessUploadSecondTest: SaveLocalFile失败", null);
                return false;
            }
            On_evt_log_handle("DataProcessUploadSecondTest: 保存本地数据", null);

            if (!m_resultObj.construct(m_isAllFail, m_timeStart, m_timeStop, m_dicResults, m_lstConifg, m_productObj, m_userObj, m_setupObj))
            {
                On_evt_log_handle("DataProcessUploadSecondTest: construct失败", null);
                return false;
            }

            if (m_productObj.iMode == (int)Running_Mode.ENG || GDefine.IS_LOCAL_RESULT_MOD) return true;
            bool ret;
            ret = m_resultObj.upload_MOBI(m_ModTestMode);
            On_evt_log_handle(string.Format("DataProcessUploadSecondTest: 保存MOBI数据({0})", ret), null);
            if (!ret)
                (m_handle as FrmMods).Tips("保存MOBI数据失败！", 0);  
            if (!GDefine.IS_LOCAL_RESULT_ZTE)
            {
                if (m_resultObj.Isvalid_ProductType_ZTE(m_productObj.sProcode))
                {
                    ret = m_resultObj.upload_ZTE();
                    On_evt_log_handle(string.Format("DataProcessUploadSecondTest: 保存ZTE数据({0})", ret), null);
                }
            }
            return true;
        }

        private bool Data()
        {
            m_timeStop = DateTime.Parse(PIMFunction.getTime("MOD"));
            MB_B = true; bool ret = false;
            List<string> listFreBand = m_resultObj.GetFreBandByProductTypeID(m_productObj.sProcode);
            string currentBand = "";
            int num = -1;
            if (listFreBand != null && listFreBand.Count > 1)
            {
                for (int i = 0; i < m_lstConifg.Count; i++)
                {
                    if (m_lstConifg[i].TestBand == null)
                    {
                        continue;
                    }
                    if (!listFreBand.Contains(m_lstConifg[i].TestBand))
                        num++;
                    if (!currentBand.Contains(m_lstConifg[i].TestBand))
                    {
                        currentBand += m_lstConifg[i].TestBand;
                        if (i != m_lstConifg.Count - 1)
                            currentBand += ",";
                    }
                    else
                    {
                        if (i == m_lstConifg.Count - 1)
                            currentBand = currentBand.Substring(0, currentBand.Length - 1);
                        continue;
                    }
                }
                string[] strs2 = currentBand.Split(',');
                //此次测试是否包含所有需要测试频段 
                if (num == -1 && listFreBand.Count == m_lstConifg.Count && strs2.Length == listFreBand.Count)
                    DataProcessUpload();
                else
                {
                    //List<testInfo> listTestIn = m_resultObj.GetLatestTestbyProductSN(m_productObj.sProductSN);
                    List<UpdatatestInfo> listTestIn = m_resultObj.GetLatestTestbyProductSN(m_productObj.sProductSN);
                    //fail情况
                    if (m_isAllFail)
                    {
                        bool b1 = false;
                        for (int i = 0; i < listTestIn.Count; i++)
                        {
                            if (listTestIn[i].TestBand != currentBand)
                            {
                                b1 = true;
                                break;
                            }
                        }


                        //已存在其他频段
                        if (listTestIn.Count > 0 && b1)
                        {

                            //获取其他频段数据
                            List<PIMTestItemInfo> iteminfo = new List<PIMTestItemInfo>();
                            for (int i = 0; i < listTestIn.Count; i++)
                            {
                                if (listTestIn[i].TestBand != currentBand)
                                {
                                    TestDataInfo ti = new TestDataInfo(listTestIn[i]);
                                    List<PIMTestItemInfo> p = m_resultObj.GetTestItembyTestInfo(ti, m_timeStop);
                                    if (p == null)
                                        continue;
                                    iteminfo.AddRange(p);
                                }

                            }

                            //合并数据上传正式数据库
                            DataProcessUpload(iteminfo);

                            //存让当前数据到临时数据库
                            if (m_productObj.iMode == (int)Running_Mode.ENG || GDefine.IS_LOCAL_RESULT_MOD)
                            {

                            }
                            else
                            {
                                UpdatatestInfo t1 = new UpdatatestInfo();
                                t1 = m_resultObj.UPdataTi(m_isAllFail, m_timeStart, m_timeStop, m_lstConifg, m_productObj, m_userObj, currentBand, true);
                                ret = m_resultObj.UploadData_TempDataBase(t1, m_resultObj.GetCurrentTestinfo(m_timeStop, m_dicResults, m_lstConifg, m_productObj, m_setupObj), true);
                                On_evt_log_handle(string.Format("DataProcessUpload: 保存临时数据({0})", ret), null);
                            }
                        }
                        else
                        { //存入当前频段到正式数据库
                            DataProcessUpload();

                            //存入当前频段到临时数据库
                            //testInfo t1=new testInfo();
                            //t1.Flag=true;
                            //t1.TestBand=currentBand;
                            if (m_productObj.iMode == (int)Running_Mode.ENG || GDefine.IS_LOCAL_RESULT_MOD)
                            {

                            }
                            else
                            {
                                UpdatatestInfo t1 = new UpdatatestInfo();
                                t1 = m_resultObj.UPdataTi(m_isAllFail, m_timeStart, m_timeStop, m_lstConifg, m_productObj, m_userObj, currentBand, true);
                                ret = m_resultObj.UploadData_TempDataBase(t1, m_resultObj.GetCurrentTestinfo(m_timeStop, m_dicResults, m_lstConifg, m_productObj, m_setupObj), true);
                                On_evt_log_handle(string.Format("DataProcessUpload: 保存临时数据({0})", ret), null);
                            }
                        }
                    }
                    else
                    {//pass情况

                        string[] strs = currentBand.Split(',');
                        //获取其他频段数据
                        List<PIMTestItemInfo> iteminfo = new List<PIMTestItemInfo>();
                        List<string> Allband = new List<string>();
                        Allband.AddRange(strs);
                        int failCount = -1;
                        for (int i = 0; i < listTestIn.Count; i++)
                        {
                            if (listTestIn[i].TestBand != currentBand)
                            {
                                string[] strTestinfo = listTestIn[i].TestBand.Split(',');
                                for (int j = 0; j < strTestinfo.Length; j++)
                                {
                                    if (!currentBand.Contains(strTestinfo[j]))
                                        Allband.Add(strTestinfo[j]);
                                }

                                TestDataInfo ti = new TestDataInfo(listTestIn[i]);
                                List<PIMTestItemInfo> p = m_resultObj.GetTestItembyTestInfo(ti, m_timeStop);
                                if (p == null)
                                    continue;
                                if (ti.IsPass.ToUpper() == GDefine.ContentFail)
                                    failCount++;
                                iteminfo.AddRange(p);
                            }
                        }


                        //所有频段都pass
                        if (failCount == -1 && GetAllV(Allband, listFreBand))
                        {
                            //合并数据上传正式数据库
                            DataProcessUpload(iteminfo);
                            //存让当前数据到临时数据库
                            if (m_productObj.iMode == (int)Running_Mode.ENG || GDefine.IS_LOCAL_RESULT_MOD)
                            {

                            }
                            else
                            {
                                UpdatatestInfo t1 = new UpdatatestInfo();
                                t1 = m_resultObj.UPdataTi(m_isAllFail, m_timeStart, m_timeStop, m_lstConifg, m_productObj, m_userObj, currentBand, true);
                                ret = m_resultObj.UploadData_TempDataBase(t1, m_resultObj.GetCurrentTestinfo(m_timeStop, m_dicResults, m_lstConifg, m_productObj, m_setupObj), true);
                                On_evt_log_handle(string.Format("DataProcessUpload: 保存临时数据({0})", ret), null);
                            }
                            //List<PIMTestItemInfo> curretniteminfo =m_resultObj.GetCurrentTestinfo( m_timeStop, m_dicResults, m_lstConifg, m_productObj, m_setupObj);
                            // if(currentBand==null ) return false;
                            // //curretniteminfo.AddRange(iteminfo);
                            // DataProcessUpload(iteminfo);
                            // testInfo
                            // m_resultObj.UploadData_TempDataBase()
                        }
                        else
                        {
                            //testInfo t1 = new testInfo();
                            //t1.Flag = true;
                            //t1.TestBand = "1800M";
                            if (m_productObj.iMode == (int)Running_Mode.ENG || GDefine.IS_LOCAL_RESULT_MOD)
                            {

                            }
                            else
                            {
                                UpdatatestInfo t1 = new UpdatatestInfo();
                                t1 = m_resultObj.UPdataTi(m_isAllFail, m_timeStart, m_timeStop, m_lstConifg, m_productObj, m_userObj, currentBand, true);
                                ret = m_resultObj.UploadData_TempDataBase(t1, m_resultObj.GetCurrentTestinfo(m_timeStop, m_dicResults, m_lstConifg, m_productObj, m_setupObj), false);
                                On_evt_log_handle(string.Format("DataProcessUpload: 保存临时数据({0})", ret), null);
                            }

                            //摩比数据
                            MB_B = false;
                            DataProcessUpload();
                            //m_resultObj.UploadData_TempDataBase(,)
                        }
                    }
                }
            }
            else
            {
                DataProcessUpload();

            }
            // List<string> freBand=m_resultObj
            return true;
        }

        private bool GetAllV(List<string> v1, List<string> v2)
        {
            if (v1.Count < v2.Count) return false;
            for (int i = 0; i < v2.Count; i++)
            {
                if (!v1.Contains(v2[i]))
                    return false;
            }
            return true;
        }


        JcPIMDataSettings getResultMaxForKnock(JcPIMDataResults result)
        {
            JcPIMDataSettings origin = toPIMDataSettings(m_config);
            JcPIMDataSettings settings = new JcPIMDataSettings();
            settings.Mode = ImMode.Time;
            settings.Order = origin.Order;
            settings.Time = m_config.TestTime;
            settings.IsKnock = origin.IsKnock;
            settings.isRandom = origin.isRandom;

            settings.TX1 = origin.TX1;
            settings.TX2 = origin.TX2;

            settings.Offset1 = origin.Offset1;
            settings.Offset2 = origin.Offset2;
            settings.Offset_RX += m_calObj.RXOffset;


            settings.Band_Name = origin.Band_Name;

            settings.F1s = result.F1;
            settings.F1e = result.F1;
            settings.F2s = result.F2;
            settings.F2e = result.F2;
            settings.RXs = result.Im_F;
            settings.RXe = result.Im_F;

            settings.Band_TX1 = origin.Band_TX1;
            settings.Band_TX2 = origin.Band_TX2;
            settings.Band_RX = origin.Band_RX;
            settings.Port_TX1 = origin.Port_TX1;
            settings.Port_TX2 = origin.Port_TX2;
            settings.Port_RX = origin.Port_RX;

            return settings;
        }

        JcPIMDataSettings toPIMDataSettings(ClsDataConfig config)
        {
            JcPIMDataSettings settings = new JcPIMDataSettings();

            if (config.IsSweepTest)
                settings.Mode = ImMode.Freq;
            else
                settings.Mode = ImMode.Time;

            if (config.SpecUnit.ToLower() == "dbm")
                settings.Unit = ImUnit.dBm;
            else
                settings.Unit = ImUnit.dBc;

            settings.Time = config.TestTime;
            settings.IsKnock = config.IsKnock;


            string iOrder = config.PIMOrder;
            int tOrder;
            if (iOrder.Contains("H"))
            {
                settings.isHigh = true;
                string[] ob = iOrder.Split('-');
                tOrder = Convert.ToInt32(ob[0]);
                settings.Order = (ImOrder)tOrder;
            }
            else
            {
                settings.isHigh = false;
                tOrder = Convert.ToInt32(iOrder);
                settings.Order = (ImOrder)tOrder;
            }


            settings.TX1 = config.F1Power;
            settings.TX2 = config.F2Power;

            settings.Offset_RX = config.ProGain * -1;

            settings.Offset1 = config.TXOffset;
            settings.Offset2 = config.TXOffset;
            settings.Offset_RX += m_calObj.RXOffset;


            if (config.TXL > config.TXH)
            {
                double temp = config.TXL;
                config.TXL = config.TXH;
                config.TXH = temp;
            }

            if (config.RXL > config.RXH)
            {
                double temp = config.RXL;
                config.RXL = config.RXH;
                config.RXH = temp;
            }

            double freq1 = config.IsSweepTest ? config.TXL : config.F1Freq;
            double freq2 = config.IsSweepTest ? config.TXH : config.F2Freq;
            foreach (var band in JcPIMDevicesBuilder.dicBands)
            {
                if (freq1 >= band.Value.range_f1_min && freq2 <= band.Value.range_f2_max)
                {
                    if (freq1 > band.Value.range_f1_max || freq2 < band.Value.range_f2_min)
                    {
                        continue;
                    }

                    string sBandName = JcPIMDevicesBuilder.dicBands[band.Key].range_name;

                    if (!JcPIMDevicesBuilder.dicDevices.ContainsKey(sBandName))
                    {
                        continue;
                    }

                    if (!JcPIMDevicesBuilder.dicDevices[sBandName].instrEnable)
                    {
                        continue;
                    }

                    settings.Band_Name = sBandName;
                    settings.InstrumentType = JcPIMDevicesBuilder.dicDevices[settings.Band_Name].instrType;

                    if (settings.Band_Name == "JOINTCOM-MBD-V" ||
                        settings.Band_Name == "JOINTCOM-LBD-V")
                        settings.Channel = 1;
                    else
                        settings.Channel = 0;

                    if (config.IsSweepTest)
                    {
                        settings.F1Set = config.TXL;
                        settings.F2Set = config.TXH;
                        settings.StepRx = config.RXStep;
                        settings.F1s = config.TXL;
                        settings.F1e = config.TXH;
                        settings.F2s = config.TXL;
                        settings.F2e = config.TXH;

                        settings.RXs = config.RXL;
                        settings.RXe = config.RXH;
                    }
                    else
                    {
                        settings.F1s = config.F1Freq;
                        settings.F1e = config.F1Freq;
                        settings.F2s = config.F2Freq;
                        settings.F2e = config.F2Freq;

                        settings.RXs = config.PIMFreq;
                        settings.RXe = config.PIMFreq;
                    }

                    break;
                }
            }

            if (settings.Band_Name == "")
            {
                return null;
            }

            settings.Band_TX1 = (byte)JcPIMDevicesBuilder.dicDevices[settings.Band_Name].instrBandIndex;
            settings.Band_TX2 = (byte)JcPIMDevicesBuilder.dicDevices[settings.Band_Name].instrBandIndex;
            settings.Band_RX = (byte)JcPIMDevicesBuilder.dicDevices[settings.Band_Name].instrBandIndex;

            settings.Port_TX1 = 0;
            settings.Port_TX2 = 0;
            settings.Port_RX = 0;

            if (m_setupObj.IsRandomOn)
            {
                if (config.Random != "0")
                {
                    double max = 0;
                    double min = 0;

                    PIMFunction.formateSpec(config.Random, ref min, ref max);
                    if (max == 0 && min == 0)
                    {
                        settings.isRandom = false;
                    }
                    else
                    {
                        if (min < -150) min = -150;
                        settings.isRandom = true;
                        settings.RandomMax = max;
                        settings.RandomMin = min;
                        settings.IsKnock = false;
                    }
                }
                else
                {
                    settings.isRandom = false;
                }
            }

            return settings;
        }
    }

    class JcPIMRecordResult
    {
        public float fValue;
        public string sPass;
        public int index;
        public JcPIMDataResults[] valus;
        public JcPIMDataResults[] valus_knock;
    }
}
